package com.cat.dataStructure;

/**
 * @author 曲大人的喵
 * @description https://leetcode.cn/problems/unique-length-3-palindromic-subsequences/description/
 * @create 2025/8/15 09:40
 * @since JDK17
 */

public class Solution13 {
    public int countPalindromicSubsequence(String s) {
        int[] pre = new int[26], suf = new int[26];
        boolean[][] h = new boolean[26][26];    // 左边和右边相同了
        int n = s.length() - 1;
        int ans = 0;
        // 记录后缀
        for (int i = n; i >= 0; i--) {
            suf[s.charAt(i) - 'a']++;
        }
        // 提前把第一个收集起来
        pre[s.charAt(0) - 'a']++;
        for (int i = 1, t; i < n; i++) {
            t = s.charAt(i) - 'a';
            suf[t]--;
            for (int j = 0; j < 26; j++) {
                if (pre[j] != 0 && suf[j] != 0 && !h[t][j]) {   // 前面和后面都有
                    ans++;
                    h[t][j] = true; // 记录下来
                }
            }
            pre[t]++;
        }
        return ans;
    }
}
